package com.desay.pangoo.itmt.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import com.desay.pangoo.itmt.controller.vo.rag.resp.PartContentMessageVo;
import com.desay.pangoo.itmt.controller.vo.rag.resp.ProductDemandRespVo;
import com.desay.pangoo.itmt.controller.vo.rag.resp.StreamMessageRespVo;
import com.desay.pangoo.itmt.entity.rag.MessageEntity;
import com.desay.pangoo.itmt.entity.rag.MessageRelationTpnEntity;
import com.desay.pangoo.itmt.entity.rag.ProductDemandEntity;
import com.desay.pangoo.itmt.repository.rag.MessageEntityRepository;
import com.desay.pangoo.itmt.repository.rag.MessageRelationTPNEntityRepository;
import com.desay.pangoo.itmt.repository.rag.ProductDemandRepository;
import com.desay.pangoo.itmt.service.AsyncAiTaskService;
import com.fasterxml.jackson.databind.ObjectMapper;

import cn.hutool.core.bean.BeanUtil;
import lombok.extern.log4j.Log4j2;

/**
 * 有关Ai异步任务执行的具体业务逻辑
 *
 * @author uids1175
 */
@Log4j2
@Service
public class AsyncAiTaskServiceImpl implements AsyncAiTaskService {

	@Autowired
	private MessageEntityRepository messageEntityRepository;

	@Autowired
	private MessageRelationTPNEntityRepository messageRelationTpnEntityRepository;

	@Autowired
	private RestTemplate restTemplate;

	@Autowired
	private ObjectMapper objectMapper;

	@Autowired
	private ProductDemandRepository productDemandRepository;

	/**
	 * 异步保存，Ai回答的新消息
	 *
	 * @param message
	 *            Ai回答的新消息
	 * @param partContentList
	 *            Ai生成的文本内容
	 */
	@Transactional(rollbackFor = Exception.class)
	@Async("asyncAIMessageExecutor")
	@Override
	public void updateNewAiMessageContent(StreamMessageRespVo message, List<PartContentMessageVo> partContentList) {
		// 保存Ai回答的新消息,并更新到数据库
		MessageEntity messageEntity = messageEntityRepository.findById(message.getMessageId()).orElse(null);
		// 没有AI记录就返回
		if (messageEntity == null) {
			return;
		}

		// 获取纯文本内容
		String content = genContent(partContentList);
		messageEntity.setContent(content);
		// 保存到数据库
		messageEntity = messageEntityRepository.save(messageEntity);

		// 保存产品需求信息
		List<ProductDemandRespVo> productDemandList = message.getProductDemandList();
		if (productDemandList == null || productDemandList.isEmpty()) {
			return;
		}

		// 保存产品需求以及相关的Tpn信息
		for (ProductDemandRespVo productDemandRespVo : productDemandList) {
			ProductDemandEntity productDemandEntity = BeanUtil.toBean(productDemandRespVo, ProductDemandEntity.class);
			productDemandEntity.setMessageId(messageEntity.getMessageId());
			// 保存产品需求
			productDemandEntity = productDemandRepository.save(productDemandEntity);

			// 保存相关的TPN数据
			ProductDemandEntity finalProductDemandEntity = productDemandEntity;
			// 跳过没有Tpn的相关数据
			if (productDemandRespVo.getTpnInfoList() == null || productDemandRespVo.getTpnInfoList().isEmpty()) {
				continue;
			}
			List<MessageRelationTpnEntity> list = productDemandRespVo.getTpnInfoList().stream()
					.map(messageRelationTpnRespVo -> {
						MessageRelationTpnEntity entity = BeanUtil.toBean(messageRelationTpnRespVo,
								MessageRelationTpnEntity.class);
						entity.setProductDemandId(finalProductDemandEntity.getProductDemandId());
						return entity;
					}).toList();
			messageRelationTpnEntityRepository.saveAll(list);
		}

	}

	/**
	 * 拼接文本内容
	 * 
	 * @param partContentList
	 *            部分内容实体的列表
	 * @return 拼接了部分内容的字符串
	 */
	private String genContent(List<PartContentMessageVo> partContentList) {
		StringBuilder sb = new StringBuilder();
		for (PartContentMessageVo vo : partContentList) {
			sb.append(vo.getContent());
		}
		return sb.toString();
	}
}
